import axios, { AxiosError } from 'axios'
import { memberLogout } from '~/composables/useLogic'

export default defineNuxtPlugin((NuxtApp) => {
  const { BASE_API, LANGUAGES_I18N = [], IS_PROD } = useRuntimeConfig().public
  const axiosInstance = axios.create({ baseURL: BASE_API })
  const { showLoading, hideLoading } = useRequestLoading()
  // process.client 用于区分服务器端和客户端的执行环境
  const isClient = process.client
  const i18n = NuxtApp.$i18n as any
  const getToken = () => localStorage && localStorage.getItem('authToken')
  const getFpId = () => localStorage && localStorage.getItem('bit_local_id')
  // 请求拦截
  axiosInstance.interceptors.request.use((reqConfig) => {
    if (!reqConfig.hideError) showLoading()
    // 可以在这设置请求头 这样的话每次请求都会携带请求头
    if (reqConfig.withAuth && isClient) reqConfig.headers['Authorization'] = getToken()
    if (reqConfig.withAuth && isClient) reqConfig.headers['bitId'] = getFpId()
    const targetI18n = (LANGUAGES_I18N as any[]).find(
      ({ code }) => code === (reqConfig.headers['lang'] || i18n.locale.value),
    )
    reqConfig.headers['lang'] = targetI18n?.reqCode || 'en'
    if (isClient) reqConfig.headers['Channel'] = localStorage.getItem('channel')
    if (IS_PROD) reqConfig.baseURL = isClient ? BASE_API : 'http://localhost:3633'
    return reqConfig
  })

  axiosInstance.interceptors.response.use(
    async (res) => {
      // 如果传hideError 则报错也不提示错误信息弹窗
      const { hideError } = res.config
      const { result, error } = res.data
      result && hideLoading()
      if (result) return res.data
      if (process.server && !hideError) {
        console.error('接口异常', error.message)
        return showError({ statusCode: 404 })
      }
      if (error.code === 600) {
        showToast({ message: 'Auth Expired', duration: 2000 })
        memberLogout()
        return res
      }
      console.error('接口异常', error.message)
      if (isClient && !hideError) showToast({ message: error.message || 'network error', duration: 2000 })
      throw new Error(error.message)
    },
    (error: AxiosError) => {
      hideLoading()
      // if (isClient && error.code !== 'ERR_CANCELED') {
      //   console.log(error)
      //   showToast({ message: 'network error', duration: 2000 })
      // }
      console.log('接口异常', error.response?.config?.url, error.message)
      throw new Error('接口异常')
    },
  )

  return {
    provide: {
      requestPost: axiosInstance.post.bind(axiosInstance),
      requestGet: axiosInstance.get.bind(axiosInstance),
    },
  }
})
